<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;

/**
 * This is the model class for table "category".
 *
 * @property string $id
 * @property string $name
 * @property integer $create_time
 * @property string $sort_no
 * @property string $pid
 * @property Category $p
 * @property Category[] $categories
 * @property Website[] $websites
 */
class Category extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'create_time'], 'required'],
            [['create_time', 'sort_no', 'pid'], 'integer'],
            [['name'], 'string', 'max' => 50],
            [['pid'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['pid' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app', '分类名称'),
            'create_time' => Yii::t('app', '创建时间'),
            'sort_no' => Yii::t('app', '排序'),
            'pid' => Yii::t('app', 'Pid'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getP()
    {
        return $this->hasOne(Category::className(), ['id' => 'pid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategories()
    {
        return $this->hasMany(Category::className(), ['pid' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getWebsites()
    {
        return $this->hasMany(Website::className(), ['category_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return CategoryQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new CategoryQuery(get_called_class());
    }

    public static function Select($selected_id, $name, $attr = '')
    {
        $key = 'category_select_options_html';
        $category_select_options_html = Yii::$app->cache->get($key);
        if ($category_select_options_html === false) {
            $categories = Category::find()->asArray()->all();
            $data = Category::list_to_tree($categories);

            $category_select_options_html = '<select name="{{name}}" {{attr}}>';
            $category_select_options_html .= '<option value="">--选择分类--</option>';
            Category::show_options($data, $category_select_options_html);
            $category_select_options_html .= '</select>';

            Yii::$app->cache->set($key, $category_select_options_html, 3600);
        }

        $category_select_options_html = str_replace('{{name}}', $name, $category_select_options_html);
        $category_select_options_html = str_replace('{{attr}}', $attr, $category_select_options_html);
        $category_select_options_html = str_replace('<option value="' . $selected_id . '"', '<option value="' . $selected_id . '" selected', $category_select_options_html);
        return $category_select_options_html;
    }

    private static function show_options($arr, &$html, $sk = '')
    {
        if (!$arr) return;
        $sk .= '--|';
        foreach ($arr as $ar) {
            $html .= '<option value="' . $ar['id'] . '" >|' . $sk . $ar['name'] . '</option>';
            if (isset($ar['children']) && is_array($ar['children'])) {
                Category::show_options($ar['children'], $html, $sk);
            }
        }
    }

    /**
     * 把返回的数据集转换成Tree
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    private static function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}

